package com.uroad.lib.widget;

import android.widget.Button;

import com.uroad.lib.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeCount extends CountDownTimerPausable {
    Button btnCode;
    long millisUntilFinished = 0;

    /**
     * @param millisInFuture    总时长(毫秒)
     * @param countDownInterval 时间间隔(毫秒)
     * @param button            点击按钮（文字显示的按钮）
     **/
    public TimeCount(long millisInFuture, long countDownInterval, Button button) {
        super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        btnCode = button;

    }

    public static String timeago(String timeStr) {
        Date date = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            date = format.parse(timeStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }

        long timeStamp = date.getTime();

        Date currentTime = new Date();
        long currentTimeStamp = currentTime.getTime();
        long seconds = (currentTimeStamp - timeStamp) / 1000;

        long minutes = Math.abs(seconds / 60);
        long hours = Math.abs(minutes / 60);
        long days = Math.abs(hours / 24);

        if (seconds <= 15) {
            return "刚刚";
        } else if (seconds < 60) {
            return seconds + "秒前";
        } else if (seconds < 120) {
            return "1分钟前";
        } else if (minutes < 60) {
            return minutes + "分钟前";
        } else if (minutes < 120) {
            return "1小时前";
        } else if (hours < 24) {
            return hours + "小时前";
        } else if (hours < 24 * 2) {
            return "昨天";
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
            String dateString = formatter.format(date);
            return dateString;
        }

    }

    @Override
    public void onFinish() {// 计时完毕时触发
        btnCode.setText("获取验证码");
        btnCode.setClickable(true);
        btnCode.setBackgroundResource(R.drawable.btn_green);
    }

    @Override
    public void onTick(long millisUntilFinished) {// 计时过程显示
        btnCode.setClickable(false);
        btnCode.setBackgroundResource(R.drawable.bg_roundretangle_gray_shape);
        btnCode.setText(millisUntilFinished / 1000 + "秒后重发");
    }

}
